package com.ceprei.gui.shiro.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhou minghao
 * @date 2024/11/28
 * @description
 */
@Component
@Slf4j
public class JwtUtils implements Serializable {

    @Autowired
    private JwtProperties jwtProperties;


    // 生成JWT令牌
    public String generateToken(String subject) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, subject);
    }

    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + jwtProperties.getExpriation()* 1000);
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256,jwtProperties.getSecret())
                .compact();
    }

    // 从令牌中获取主体信息（通常是用户名等标识用户的内容）
    public String getSubjectFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims!= null? claims.getSubject() : null;
    }

    // 解析令牌获取Claims对象
    private Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 验证令牌是否有效
    public boolean validateToken(String token) {
        return getSubjectFromToken(token)!= null &&!isTokenExpired(token);
    }

    // 判断令牌是否过期
    private boolean isTokenExpired(String token) {
        Date expirationDate = getExpirationDateFromToken(token);
        return expirationDate.before(new Date());
    }

    // 从令牌中获取过期时间
    private Date getExpirationDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims!= null? claims.getExpiration() : null;
    }
}
